import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LargestDivisibleSubset {

    public static void main(String[] args) {
        LargestDivisibleSubset largestDivisibleSubset = new LargestDivisibleSubset();
        int[] nums = {4,8,10,240};
        System.out.println(largestDivisibleSubset.largestDivisibleSubset(nums));
    }

    public List<Integer> largestDivisibleSubset(int[] nums) {
        Arrays.sort(nums);
        int n  = nums.length;
        int[] dp = new int[n];
        dp[0] = 1;
        int max = 1;
        int index = 0;
        for (int i = 1; i < n; i++) {
            dp[i] = 1;
            for (int j = i - 1; j >= 0; j--) {
                dp[i] = Math.max(dp[i], nums[i] % nums[j] == 0 ? dp[j] + 1 : 1);
            }
            if (max <= dp[i]) {
                max = dp[i];
                index = i;
            }
        }
        List<Integer> ans = new ArrayList<>();
        ans.add(nums[index]);
        for (int i = index; i >= 0 && max > 1; i--) {
            if (dp[i] == max - 1 && nums[index] % nums[i] == 0) {
                ans.add(nums[i]);
                max = dp[i];
                index = i;
            }
        }
        return ans;
    }


}
